package cn.dm.Colloer;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class DMColloer {
@/**
 * 用户登录
 *
 * @param phone
 * @param password
 * @param vcode
 * @return
 */
@RequestMapping(value = "/v/login", method = RequestMethod.POST)
public Dto userLogin(
        @RequestParam(value = "phone", required = true) String phone,
        @RequestParam(value = "password", required = false)String password,
        @RequestParam(value = "vcode", required = false) String vcode) throws Exception {
    String tokenKey = null;
    Map<String,Object> map=new HashMap<>();
    Integer count=null;
    String ma=null;
    DmUserVO dmUserVO=null;




    if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isEmpty(password)&&EmptyUtils.isEmpty(vcode)){
        //============================手机验证码发送===========================
        //=====1手机号格式是否正确
        if(loginDmUser.validPhon(phone)){
            //=====2正确的话判断是否未注册
            map.put("phone",phone);
            count=restDmUserClient.getDmUserCountByMap(map);
            if(count<0){
                //未注册返回异常消息
                return  DtoUtil.returnFail(ErrorCode.PHONE_NO_REGISTER.getErrorMessage(),ErrorCode.PHONE_NO_REGISTER.getErrorCode());
            }else{
                try {
                    //=====3发送验证码并且判断验证码是否在有效期
                    //存在有效期
                    if(redisUtils.exist(Constants.LoginAndRegisterCode.login+phone)){
                        //异常消息
                        return DtoUtil.returnFail(ErrorCode.ONE_60_SECOND.getErrorMessage(),ErrorCode.ONE_60_SECOND.getErrorCode());
                    }
                    //发送验证码
                    ma=loginDmUser.sendPhon(Constants.LoginAndRegisterCode.login,phone);
                }catch (Exception e){
                    //发送验证码时的异常捕捉
                    return DtoUtil.returnFail(ErrorCode.VERIFICATION_SEND_ERROR.getErrorMessage(),ErrorCode.VERIFICATION_SEND_ERROR.getErrorCode());
                }
            }
        }



    }else if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isEmpty(password)&&EmptyUtils.isNotEmpty(vcode)){
        //============================手机验证码登录===========================
        //=====1：验证码验证
        if(redisUtils.exist(Constants.LoginAndRegisterCode.login+phone)){
            //获取redis的验证码
            ma=redisUtils.get(Constants.LoginAndRegisterCode.login+phone).toString();
        }else{
            ma=null;
        }
        if(vcode.equals(ma)){
            //=====1；成功
            //根据手机号获取用户信息
            dmUserVO = loginDmUser.queryUser_PhoneAndPassword(phone, null);
            //判断有无token
            tokenKey = tokenService.validateToken(dmUserVO.getUserId().toString());
            //无token
            if (EmptyUtils.isEmpty(tokenKey)) {
                //=====1:生成token并储存redis
                //生成token
                tokenKey = tokenService.getToken("PC", dmUserVO);
                //储存token
                tokenService.saveTokenById(dmUserVO.getUserId().toString(), tokenKey);
                tokenService.saveToken(tokenKey, dmUserVO);
            }
        }else if(!vcode.equals(ma)){
            //=====2：失败
            return DtoUtil.returnFail(ErrorCode.CODE_ERROR.getErrorMessage(),ErrorCode.CODE_ERROR.getErrorCode());
        }





    }else if(EmptyUtils.isNotEmpty(phone)&&EmptyUtils.isNotEmpty(password)&&EmptyUtils.isEmpty(vcode)) {

        //============================手机和密码登录===========================
        //=====1:获取用户相关信息
        dmUserVO = loginDmUser.queryUser_PhoneAndPassword(phone, password);
        //=====2：登录失败
        if (EmptyUtils.isEmpty(dmUserVO)) {
            //kafKaUtil.sendInfoMessage("登录失败！");
            return DtoUtil.returnFail(ErrorCode.PHONE_AND_PASSWORD_ERROR.getErrorMessage(), ErrorCode.PHONE_AND_PASSWORD_ERROR.getErrorCode());

        } else {
            //=====3：登录成功
            //=====1：判断有无token
            tokenKey = tokenService.validateToken(dmUserVO.getUserId().toString());
            //无token
            if (EmptyUtils.isEmpty(tokenKey)) {
                //=====1:生成token并储存redis
                //生成token
                tokenKey = tokenService.getToken("PC", dmUserVO);
                //储存token
                tokenService.saveTokenById(dmUserVO.getUserId().toString(), tokenKey);
                tokenService.saveToken(tokenKey, dmUserVO);
            }
        }
    }

    //返回用户信息和token到客户端
    return DtoUtil.returnSuccess(ErrorCode.LOGIN_SUCCESS.getErrorMessage(),loginDmUser.mergeByUser_Token(tokenKey, dmUserVO));

}


    /**
     * 用户退出
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/v/loginOut", method = RequestMethod.POST)
    public Dto outLogin(@RequestParam(value = "token", required = true) String token) throws Exception {
        //=========判断token是否过期
        String tokenValue = tokenService.validateToken(token);
        DmUser dmUser = JSONObject.parseObject(tokenValue, DmUser.class);
        if (EmptyUtils.isNotEmpty(tokenValue)) {
            //执行退出
            tokenService.deleteToken(token);
            tokenService.deleteToken(dmUser.getId().toString());
            //如果有其他业务数据，也需要销毁，未完待续
            //。。。。。。。。
            return DtoUtil.returnSuccess();
        } else {
            return DtoUtil.returnFail(ErrorCode.TOKEN_NO.getErrorMessage(), ErrorCode.TOKEN_NO.getErrorCode());
        }
    }




}
